﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace ENG.PSSAirbusSoundExtender
{
  public partial class FrmCalibrate : Form
  {
    public FrmCalibrate()
    {
      this.Activated += new EventHandler(FrmCalibrate_Activated);
      this.Deactivate += new EventHandler(FrmCalibrate_Deactivate);
      Program.CalibrationClick += new Program.ClickHandler(Program_CalibrationClick);
      InitializeComponent();
    }

    void FrmCalibrate_Deactivate(object sender, EventArgs e)
    {
      isActive = false;
    }

    private bool isActive = false;
    void FrmCalibrate_Activated(object sender, EventArgs e)
    {
      isActive = true;
    }

    void Program_CalibrationClick(Point point)
    {
      if (!isActive)
        lst.Items.Add(point);
    }

    private void btnRemoveSelected_Click(object sender, EventArgs e)
    {
      List<object> remLst = new List<object>();
      foreach (var fItem in lst.SelectedItems)
      {
        remLst.Add(fItem);        
      } // foreach (var fItem in lst.SelectedItems)

      foreach (var fItem in remLst)
      {
        lst.Items.Remove(fItem);
      } // foreach (var fItem in sel)
    }

    private void btnOk_Click(object sender, EventArgs e)
    {
      if (lst.Items.Count == 0)
      {
        MessageBox.Show("Unable to get rectangle from no data. Insert some data or close the window by top-right cross button.");
        return;
      }
      Rectangle? ret = null;

      foreach (var fItem in lst.Items)
      {
        Point inn = (Point) fItem;

        if (ret == null)
        {
          ret = new Rectangle(inn, new Size(1,1));
        }
        else
        {
          int left = Math.Min(ret.Value.Left, inn.X);
          int right = Math.Max(ret.Value.Right, inn.X);
          int top = Math.Min(ret.Value.Top, inn.Y);
          int bottom = Math.Max(ret.Value.Bottom, inn.Y);
          int width = right - left;
          int height = bottom - top;

          ret = new Rectangle(new Point(left, top), new Size(width, height));
        }
      } // foreach (var fItem in lst.Items)

      result = ret.Value;
      this.Hide();
    }

    public string ButtonName { get { return txtName.Text; } set { txtName.Text = value; } }

    private Rectangle result;
    public Rectangle Rectangle { get { return result; } }
  }
}
